package com.xingchen.springboot3.exception;

import com.xingchen.springboot3.common.bean.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;



/**
 *
 * @author weijingchen
 * @DateTime 2025-09-24
 */
@RestControllerAdvice
public class GlobalExceptionHander {

    @ExceptionHandler(HandlerMethodValidationException.class)
    public Result handleValidationException(HandlerMethodValidationException e) {
            e.printStackTrace();
        return Result.error(StringUtils.hasLength(e.getMessage())?e.getMessage():"参数校验失败");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder errorMessage = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(error -> {
            if (!errorMessage.isEmpty()) {
                errorMessage.append("; ");
            }
            errorMessage.append(error.getDefaultMessage());
        });
        return Result.error(errorMessage.toString());
    }
}

